package com.technology.education.ui.student.publish

import android.app.Activity
import android.content.Intent
import android.graphics.Typeface
import android.os.Build
import android.widget.TextView
import androidx.core.os.bundleOf
import com.afollestad.materialdialogs.LayoutMode
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.bottomsheets.BottomSheet
import com.afollestad.materialdialogs.bottomsheets.expandBottomSheet
import com.afollestad.materialdialogs.bottomsheets.setPeekHeight
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.angcyo.dsladapter.*
import com.blankj.utilcode.util.SnackbarUtils.dismiss
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.technology.education.R
import com.technology.education.base.BaseRecyclerTopBarFragment
import com.technology.education.data.SpKeys
import com.technology.education.data.model.TeacherInfoModel
import com.technology.education.dslitem.ItemSingleButton
import com.technology.education.dslitem.ItemSingleEdit
import com.technology.education.dslitem.module.ItemPublishImage
import com.technology.education.ext.*
import com.technology.education.utils.MediaUtils
import com.technology.education.widget.CommonButton
import com.theartofdev.edmodo.cropper.CropImage
import me.hgj.jetpackmvvm.ext.parseState


/**
 * 发布需求,接收教师id
 * 如果id 为空则说明不指定教师,底部两个按钮都展示出来
 * 如果不为空,则为指定教师,只有发布按钮
 */
class PublishFragment : BaseRecyclerTopBarFragment<PublishViewModel>() {
    override fun initViews() {
        setTitle("发布辅导需求")
        mViewModel.teacherId = arguments?.getString("id")
        initGrid(4)
    }

    override fun lazyLoadData() {
        setUI()
    }

    private fun setUI() {
        renderAdapter {
            dslItem(R.layout.item_publish) {
                itemSpanCount = -1
                itemTag = "photo"
                itemBindOverride = { itemHolder, itemPos, _, _ ->
                    itemHolder.clickItem {
                        showDialog(itemPos)
                    }
                }
            }

            dslItem(R.layout.item_publish_button) {
                itemBindOverride = { itemHolder, itemPos, _, _ ->
                    itemSpanCount = -1
                    itemHolder.click(R.id.button) {
                        updateOrInsertItem<ItemSingleEdit>("input", itemPos + 1) {
                            it.apply {
                                itemTag = "input"
                                hintS = "请描述您所遇到的问题"
                                maxLine = 10
                                minLine = 8
                                itemBottomInsert = 12 * dpi
                                itemBindOverride = { itemHolder, _, _, _ ->
                                    itemTag = "input"
                                    itemHolder.et(R.id.et_content)?.background =
                                        getResId(R.drawable.box_login_edit)
                                }
                            }
                        }
                    }
                }
            }

            if (mViewModel.teacherId == null) {
                ///如果当前没有接收到指定老师id,则两种按钮都展示
                dslItem(ItemSingleButton("自动匹配老师（推荐）", tag = "auto")) {
                    style.lineHeight = 0
                    itemClick = {
                        commitData()
                    }
                }
                dslItem(ItemSingleButton("手动挑选老师")) {
                    itemBindOverride = { itemHolder, _, _, _ ->
                        itemTag = "pick"
                        style.lineHeight = 0
                        itemHolder.v<CommonButton>(R.id.button)?.apply {
                            background = getResId(R.drawable.bg_round_blue_line)
                            setTextColor(getColor(R.color.theme_color))
                        }
                        itemHolder.click(R.id.button) {
                            navigation(it, R.id.action_publishFragment_to_teacherListFragment)
                        }
                    }
                }
            } else {
                dslItem(ItemSingleButton("发布需求", tag = "publish")) {
                    style.lineHeight = 0
                    itemClick = {
                        commitData()
                    }
                }
            }

        }
    }

    private fun showDialog(itemPos: Int) {
        this.itemPos = itemPos
        MaterialDialog(requireContext(), BottomSheet(LayoutMode.WRAP_CONTENT)).cornerRadius(8f)
            .customView(R.layout.dialog_select_camera)//.title(text = "上传图片")//.setPeekHeight(160 * dpi)
            .show {
                getCustomView().findViewById<TextView>(R.id.tv_cancel)?.setOnClickListener {
                    dismiss()
                }
                getCustomView().findViewById<TextView>(R.id.tv_album)?.setOnClickListener {
                    selectPhoto(
                        count = 1,
                        selectedList = mViewModel.selectPhoto as ArrayList<Photo>,
                        showCamera = false
                    ) {
                        cropImage(it, itemPos)
                    }
                    dismiss()
                }
                getCustomView().findViewById<TextView>(R.id.tv_camera)?.setOnClickListener {
                    EasyPhotos.createCamera(
                        this@PublishFragment,
                        false
                    )
                        .setFileProviderAuthority("com.technology.education.fileprovider")//参数说明：见下方`FileProvider的配置`
                        .start(333)
                    dismiss()
                }
            }
    }

    private var itemPos = 0
    private fun cropImage(it: ArrayList<Photo>, itemPos: Int) {
        this.itemPos = itemPos
        if (it.isNotEmpty()) {
            val photo = it[0]
            CropImage.activity(photo.uri)
                .setAutoZoomEnabled(false)
                .setMultiTouchEnabled(false)
                .setMaxZoom(2)
                .setAllowFlipping(false)
                .start(requireContext(), this)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && data != null) {
            if (requestCode == 333) {
                val resultPhotos: ArrayList<Photo>? =
                    data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS)
                if (resultPhotos != null && resultPhotos.isNotEmpty()) {
                    cropImage(resultPhotos, itemPos)
                }
            }

            if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
                val result = CropImage.getActivityResult(data)
                val resultUri = result.uri
                showLog("onActivityResult------$resultUri")
                val photo = Photo(
                    "${System.currentTimeMillis()}.png",
                    resultUri,
                    MediaUtils.getFilePathFromUri(requireContext(), resultUri),
                    0,
                    0,
                    0,
                    0,
                    0, 0, "png"
                )
                mViewModel.selectPhoto.add(
                    photo
                )
                insertImages(itemPos)
            }

        }

    }

    private fun commitData() {
        mViewModel.question = myAdapter.getItemText("input") ?: ""
        if (mViewModel.selectPhoto.isEmpty()) {
            toast("请上传您遇到的问题")
            return
        }
        showLoading()
        getAppViewModel().upload(mViewModel.selectPhoto) {
            mViewModel.commit(it)
        }
    }


    private fun insertImages(pos: Int) {
        renderAdapter {
            mViewModel.selectPhoto.forEachIndexed { index, photo ->
                updateOrInsertItem<ItemPublishImage>(photo.path, pos + 1 + index) { it ->
                    it.apply {
                        itemTopInsert = 24 * dpi
                        itemBottomInsert = 16 * dpi
                        itemDecorationColor = getColor(R.color.white)
                        imgUrl = photo.path
                        itemSpanCount = 1
                        itemClick = { view ->
                            if (view.id == R.id.iv_del) {
                                removeItem(itemTag = itemTag)
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    mViewModel.selectPhoto.removeIf { del ->
                                        del.path == itemTag
                                    }
                                }
                            } else {
                                val photos = arrayListOf<String>()
                                mViewModel.selectPhoto.forEach {p->
                                    photos.add(p.path)
                                }

                                toPreviewPhoto(index, photos)
                            }
                        }
                    }

                }
            }
            updateAllItem()
        }
    }

    override fun createObserver() {
        mViewModel.result.observe(this) {
            dismissLoading()
            parseState(it, onSuccess = { it ->
                if (it.state == "1") {
                    customDialog(
                        "提示",
                        notify = "您账户余额不足,是否进行充值?",
                        confirmStr = "立即充值",
                        cancelStr = "稍后充值",
                        cancel = {}) {
                        navigation(requireView(), R.id.action_publishFragment_to_depositFragment)
                    }
                } else {
                    navigation(
                        requireView(), R.id.action_publishFragment_to_orderDetailFragment,
                        bundleOf("id" to it.id)
                    )
                }

            }, onError = { it ->
                if (mViewModel.teacherId != null) {
                    ///如果已经选择了教师,并且有publish的item,则说明是从收藏列表跳转过来的
                    ///要去除publish item,同时增加 手动和自动两个item
                    setButton()
                }
                toast(it.errorMsg)
            })
        }

        observe(SpKeys.SELECT_TEACHER, TeacherInfoModel::class.java) {
            mViewModel.teacherId = it.id
            commitData()
        }
    }

    private fun setButton() {
        renderAdapter {
            if (findItemByTag("publish") != null) {
                removeItem("publish")
                dslItem(ItemSingleButton("自动匹配老师（推荐）", tag = "auto")) {
                    style.lineHeight = 0
                    itemClick = {
                        commitData()
                    }
                }
                dslItem(ItemSingleButton("手动挑选老师")) {
                    itemBindOverride = { itemHolder, _, _, _ ->
                        itemTag = "pick"
                        style.lineHeight = 0
                        itemHolder.v<CommonButton>(R.id.button)?.apply {
                            background = getResId(R.drawable.bg_round_blue_line)
                            setTextColor(getColor(R.color.theme_color))
                        }
                        itemHolder.click(R.id.button) {
                            navigation(it, R.id.action_publishFragment_to_teacherListFragment)
                        }
                    }
                }
            }
        }
    }
}